package com.hyb.config;

import com.hyb.pojo.Role;
import com.hyb.pojo.User;
import com.hyb.service.RoleService;
import com.hyb.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


//自定义的UserRealm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//拿到对象
        Role role = roleService.getById(currentUser.getRole_id());
        info.addStringPermission(role.getR_name());
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken userToken=(UsernamePasswordToken) authenticationToken;
        User user=userService.getByName(userToken.getUsername());
        if (user==null){
            return null;//UnknownAccountException
        }
            //密码认证
        return new SimpleAuthenticationInfo(user,user.getPwd(),"");
    }
}
